// Login.tsx
import React, { useState } from 'react';
import { Form, Input, Button, message, Card, Row, Col } from 'antd';
import { UserLogin } from '../type/UserLogin';
import userApi from '../api/api';
import { Link, useNavigate } from 'react-router-dom';
import { UserOutlined, LockOutlined } from '@ant-design/icons'; // 确保同时导入这两个图标

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values: UserLogin) => {
    setLoading(true);
    try {
      const response = await userApi.login(values);
      if (response.data.message === '登录成功') {
        message.success('登录成功');
        navigate("/home");
      } else {
        message.error('用户名或密码错误');
      }
    } catch (error) {
      message.error('登录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Row gutter={16} style={{ height: '100vh' }}>
      <Col span={12} offset={6}>
        <Card title="登录" style={{ width: '100%', maxWidth: 400, margin: 'auto' }}>
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            style={{ padding: '20px' }}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input placeholder="用户名" prefix={<UserOutlined />} />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password placeholder="密码" prefix={<LockOutlined />} />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                block
              >
                登录
              </Button>
              <Link to={"register"}>注册</Link>
             </Form.Item>
          </Form>
        </Card>
      </Col>
    </Row>
  );
};

export default Login;